<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<jsp:include page="header.jsp"/>

<style>
    :root {
        --bs-primary: #3b7ddd;
        --bs-primary-rgb: 59, 125, 221;
        --bs-success: #1cbb8c;
        --bs-success-rgb: 28, 187, 140;
        --bs-danger: #fc5b69;
        --bs-danger-rgb: 252, 91, 105;
        --bs-warning: #f7b84b;
        --bs-warning-rgb: 247, 184, 75;
        --bs-light-bg: #f5f7fa;
    }

    .card {
        border-radius: 0.5rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        border: none;
        margin-bottom: 1.5rem;
    }

    .card-header {
        background-color: #fff;
        border-bottom: 1px solid #eaeef1;
        padding: 1rem 1.25rem;
        font-weight: 600;
        color: #2c3e50;
    }

    .table-container {
        background-color: #fff;
        border-radius: 0.5rem;
        overflow: hidden;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }

    .table th {
        background-color: var(--bs-light-bg);
        color: #2c3e50;
        font-weight: 600;
        padding: 0.75rem 1rem;
        border-top: none;
    }

    .table td {
        padding: 0.75rem 1rem;
        vertical-align: middle;
    }

    .status-badge {
        padding: 0.35em 0.65em;
        border-radius: 0.25rem;
        font-size: 0.75em;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .bg-enabled {
        background-color: rgba(var(--bs-success-rgb), 0.15);
        color: var(--bs-success);
    }

    .bg-disabled {
        background-color: rgba(var(--bs-danger-rgb), 0.15);
        color: var(--bs-danger);
    }

    .action-btn {
        padding: 0.25rem 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.875rem;
    }
    .search-box {
        position: relative;
        margin-bottom: 0.5rem;
    }

    .search-box .form-control {
        border-radius: 2rem;
        padding-left: 2.75rem;
        padding-right: 1rem;
        height: calc(2.5rem + 2px);
        border: 2px solid #e9ecef;
        transition: border-color 0.2s ease, box-shadow 0.2s ease;
    }

    .search-box .form-control:focus {
        border-color: var(--bs-primary);
        box-shadow: 0 0 0 0.25rem rgba(59, 125, 221, 0.15);
    }

    .search-box .bi {
        position: absolute;
        left: 1.25rem;
        top: 50%;
        transform: translateY(-50%);
        color: #6c757d;
        z-index: 10;
        font-size: 1.1rem;
    }

    .search-actions {
        display: flex;
        gap: 0.75rem;
        flex-wrap: wrap;
        align-items: center;
    }

    /* 动画效果 */
    .fade-in {
        animation: fadeIn 0.3s ease-in;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
</style>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">课程管理系统</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <button type="button" class="btn btn-sm btn-outline-secondary">
                <i class="bi bi-file-earmark-plus"></i> 导出
            </button>
            <button type="button" class="btn btn-sm btn-outline-secondary">
                <i class="bi bi-printer"></i> 打印
            </button>
        </div>

    </div>
</div>

<c:if test="${not empty courseSearchText or not empty subjectSearchText}">
    <div class="card mb-3">
        <div class="card-body d-flex justify-content-between align-items-center flex-wrap">
            <div class="flex-grow-1 mb-2 mb-md-0">
                <h5 class="card-title">
                    <i class="bi bi-search me-2"></i>搜索结果
                </h5>
                <p class="mb-0 text-muted">
                    <c:if test="${not empty subjectSearchText}">
                        专业名称: <strong>${subjectSearchText}</strong>
                    </c:if>
                    <c:if test="${not empty courseSearchText}">
                        课程名称: <strong>${courseSearchText}</strong>
                        <c:if test="${not empty subjectSearchText}">
                            <span class="mx-2">|</span>
                        </c:if>
                    </c:if>
                    <span class="mx-2">|</span>
                    找到 <strong>${page.currentPage}</strong> 个课程
                </p>
            </div>
            <form action="${pageContext.request.contextPath}/coursemanage/sort" method="get">
                <input type="hidden" name="subjectSearchText" value="${subjectSearchText}">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-list-stars"></i> 课程排序
                </button>
            </form>
        </div>
    </div>
</c:if>


<!-- 卡片中的搜索部分 -->
<div class="card fade-in">
    <div class="card-body">
        <form action="${pageContext.request.contextPath}/coursemanage/search" method="get" id="searchForm">
            <div class="row g-3 align-items-center">
                <div class="col-md-5">
                    <div class="search-box">
                        <i class="bi bi-search"></i>
                        <input type="text" class="form-control" placeholder="输入查找的专业"
                               id="subjectSearchInput" name="subjectSearchText" value="${subjectSearchText}">
                    </div>
                </div>
                <div class="col-md-5">
                    <div class="search-box">
                        <i class="bi bi-search"></i>
                        <input type="text" class="form-control" placeholder="输入查找的课程"
                               id="courseSearchInput" name="courseSearchText" value="${courseSearchText}">
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="search-actions">
                        <button class="btn btn-primary" type="submit" id="searchBtn">
                            <i class="bi bi-search"></i> 查询
                        </button>
                        <button class="btn btn-success" type="button"
                                onclick="window.location.href='${pageContext.request.contextPath}/coursemanage/addcourse'">
                            <i class="bi bi-plus-circle"></i> 添加课程
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>


<!-- 数据表格 -->
<div class="table-container fade-in">
    <div class="table-responsive">
        <table class="table table-hover" id="courseTable">
            <thead>
            <tr>
                <th scope="col">ID</th>
                <th scope="col">专业科目</th>
                <th scope="col">课程名称</th>
                <th scope="col">课程描述</th>
                <th scope="col">创建时间</th>
                <th scope="col">状态</th>
                <th scope="col">操作</th>
            </tr>
            </thead>
            <!-- 修改空数据判断 -->
            <c:if test="${empty page.items}">
                <tr>
                    <td colspan="7" class="text-center">暂无课程数据</td>
                </tr>
            </c:if>
            <c:forEach items="${page.items}" var="course" varStatus="status">
                <tr>
                    <td>${(page.pageIndex - 1) * page.pageSize + status.index + 1}</td>
                    <td>
                        <c:forEach items="${subjects}" var="subject">
                            <c:if test="${subject.id == course.subjectId}">
                                ${subject.name}
                            </c:if>
                        </c:forEach>
                    </td>
                    <td>${course.name}</td>
                    <td>${course.description}</td>
                    <td>${course.createDate}</td>
                    <td>
                        <c:choose>
                            <c:when test="${course.state}">
                                <span class="status-badge bg-enabled">启用</span>
                            </c:when>
                            <c:otherwise>
                                <span class="status-badge bg-disabled">禁用</span>
                            </c:otherwise>
                        </c:choose>
                    </td>

                    <td>
                        <button class="btn btn-sm btn-outline-primary action-btn"
                                onclick="window.location.href='${pageContext.request.contextPath}/coursemanage/update?id=${course.id}'">
                            <i class="bi bi-pencil me-1"></i>编辑
                        </button>
                        <!-- 修改删除按钮 -->
                        <button class="btn btn-sm btn-outline-danger action-btn"
                                onclick="showDeleteModal(${course.id}, '${course.name}')">
                            <i class="bi bi-trash me-1"></i>删除
                        </button>
                        <!-- 添加查找代课老师按钮 -->
                        <button class="btn btn-sm btn-outline-info action-btn"
                                onclick="showCourseTeachersModal(${course.id}, '${course.name}')">
                            <i class="bi bi-person-lines-fill me-1"></i>设置老师
                        </button>

                    </td>
                </tr>
            </c:forEach>
        </table>
        <jsp:include page="pagination.jsp"/>
    </div>
</div>

<!-- 查看和设置课程老师 Modal -->
<div class="modal fade" id="courseTeachersModal" tabindex="-1" aria-labelledby="courseTeachersModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="courseTeachersModalLabel">课程代课老师管理</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <h6>课程名称: <span id="modalCourseName"></span></h6>
                    <input type="hidden" id="modalCourseId">
                </div>

                <div class="card mb-3">
                    <div class="card-header">
                        <h6 class="mb-0">已代课老师</h6>
                    </div>
                    <div class="card-body">
                        <div id="assignedTeachersList">
                            <!-- 已分配老师将在这里动态加载 -->
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">添加老师</h6>
                    </div>
                    <div class="card-body">
                        <form id="addTeacherToCourseForm">
                            <div class="row g-3">
                                <div class="col-md-8">
                                    <select class="form-select" id="availableTeachersSelect" required>
                                        <option value="">加载中...</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <button type="submit" class="btn btn-primary w-100">
                                        <i class="bi bi-plus-circle"></i> 添加
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel"
     aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteConfirmModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除这个课程吗？此操作不可恢复！</p>
                <p>课程ID: <span id="deleteCourseId"></span></p>
                <p>课程名称: <span id="deleteCourseName"></span></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
            </div>
        </div>
    </div>
</div>

<!-- 操作结果Modal -->
<div class="modal fade" id="resultModal" tabindex="-1" aria-labelledby="resultModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="resultModalLabel">操作结果</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center">
                <i id="resultIcon" class="bi" style="font-size: 3rem;"></i>
                <h5 id="resultTitle" class="mt-3"></h5>
                <p id="resultMessage" class="mb-0"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
            </div>
        </div>
    </div>
</div>


<script>
    // 显示课程老师管理模态框
    window.showCourseTeachersModal = function showCourseTeachersModal(courseId, courseName) {
        // 设置模态框标题和课程信息
        document.getElementById('modalCourseName').textContent = courseName;
        document.getElementById('modalCourseId').value = courseId;

        // 加载已分配的老师
        loadAssignedTeachers(courseId);

        // 加载可分配的老师列表
        loadAvailableTeachers(courseId);

        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('courseTeachersModal'));
        modal.show();
    }
    // 加载课程的老师
    function loadAssignedTeachers(courseId) {
        const assignedTeachersList = document.getElementById('assignedTeachersList');
        assignedTeachersList.innerHTML = '<div class="text-center"><div class="spinner-border" role="status"><span class="visually-hidden">加载中...</span></div></div>';

        fetch('${pageContext.request.contextPath}/coursemanage/getCourseTeachers?courseId=' + courseId)
            .then(response => response.json())
            .then(data => {
                if (data && data.length > 0) {
                    let html = '<div class="row">';
                    data.forEach(teacher => {
                        html +=
                            "<div class='col-md-6 mb-2'>"+
                            "<div class='d-flex justify-content-between align-items-center p-2 border rounded'>"+
                            "<div>"+
                            "<strong>"+teacher.name+"</strong>"+
                            "</div>"+
                            "<button type='button' class='btn btn-sm btn-danger' onclick='removeTeacherFromCourse("+courseId+", "+teacher.id+", \""+teacher.name+"\")'>"+
                            "<i class='bi bi-trash'></i>"+
                            "</button>"+
                            "</div>"+
                            "</div>";
                    });
                    html += '</div>';
                    assignedTeachersList.innerHTML = html;
                } else {
                    assignedTeachersList.innerHTML = '<div class="alert alert-info">该课程暂无分配老师</div>';
                }
            })
            .catch(error => {
                console.error('加载已分配老师失败:', error);
                assignedTeachersList.innerHTML = '<div class="alert alert-danger">加载已分配老师失败</div>';
            });
    }

    // 加载老师列表
    function loadAvailableTeachers(courseId) {
        const teacherSelect = document.getElementById('availableTeachersSelect');
        teacherSelect.innerHTML = '<option value="">加载中...</option>';

        // 移除 courseId 参数，因为后端方法现在返回所有老师
        fetch('${pageContext.request.contextPath}/coursemanage/getAvailableTeachers')
            .then(response => {
                return response.json();
            })
            .then(data => {
                console.log(data)
                if (data && data.length > 0) {
                    let options = '<option value="">请选择老师</option>';
                    data.forEach(teacher => {
                        options += "<option value=" + teacher.id + ">" + teacher.name + "</option>";
                    });
                    teacherSelect.innerHTML = options;
                } else {
                    teacherSelect.innerHTML = '<option value="">无可用老师</option>';
                }
            })
            .catch(error => {
                console.error('加载可分配老师失败:', error);
                teacherSelect.innerHTML = '<option value="">加载失败</option>';
            });
    }

    // 从课程中移除老师
    function removeTeacherFromCourse(courseId, teacherId, teacherName) {
        // 确认是否要移除老师
        if (confirm(`确定要从该课程中移除老师 "${teacherName}" 吗？`)) {
            // 发送请求到后端移除老师
            fetch('${pageContext.request.contextPath}/coursemanage/removeCourseTeacher', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: 'courseId=' + courseId + '&teacherId=' + teacherId
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showAutoDismissModal('移除老师成功', true);
                        // 重新加载已分配老师列表
                        loadAssignedTeachers(courseId);
                        // 重新加载可分配老师列表
                        loadAvailableTeachers(courseId);
                    } else {
                        showAutoDismissModal(data.message || '移除老师失败', false);
                    }
                })
                .catch(error => {
                    console.error('移除老师失败:', error);
                    showAutoDismissModal('移除老师失败: ' + error.message, false);
                });
        }
    }




    document.addEventListener('DOMContentLoaded', function () {
        // 获取表单和输入元素
        const searchForm = document.getElementById('searchForm');
        const courseSearchInput = document.getElementById('courseSearchInput');
        const subjectSearchInput = document.getElementById('subjectSearchInput');
        const searchBtn = document.getElementById('searchBtn');

        // 为课程搜索框添加回车事件
        if (courseSearchInput) {
            courseSearchInput.addEventListener('keyup', function (e) {
                if (e.key === 'Enter') {
                    // 检查是否有内容需要搜索
                    const courseText = courseSearchInput.value.trim();
                    const subjectText = subjectSearchInput ? subjectSearchInput.value.trim() : '';

                    if (courseText !== '' || subjectText !== '') {
                        searchForm.submit();
                    }
                }
            });
        }

        // 为专业搜索框添加回车事件
        if (subjectSearchInput) {
            subjectSearchInput.addEventListener('keyup', function (e) {
                if (e.key === 'Enter') {
                    // 检查是否有内容需要搜索
                    const courseText = courseSearchInput ? courseSearchInput.value.trim() : '';
                    const subjectText = subjectSearchInput.value.trim();

                    if (courseText !== '' || subjectText !== '') {
                        searchForm.submit();
                    }
                }
            });
        }

        // 点击查询按钮时触发表单提交
        if (searchBtn) {
            searchBtn.addEventListener('click', function (e) {
                e.preventDefault(); // 阻止默认行为

                // 检查是否有内容需要搜索
                const courseText = courseSearchInput ? courseSearchInput.value.trim() : '';
                const subjectText = subjectSearchInput ? subjectSearchInput.value.trim() : '';

                if (courseText !== '' || subjectText !== '') {
                    searchForm.submit();
                }
            });
        }

        // 处理添加老师到课程的表单提交
        document.getElementById('addTeacherToCourseForm').addEventListener('submit', function(e) {
            e.preventDefault();

            const courseId = document.getElementById('modalCourseId').value;
            const teacherId = document.getElementById('availableTeachersSelect').value;

            if (!teacherId) {
                showAutoDismissModal('请选择要添加的老师', false);
                return;
            }

            fetch('${pageContext.request.contextPath}/coursemanage/addTeacherToCourse', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: "courseId="+courseId+"&teacherId="+teacherId
                    <%--`courseId=${courseId}&teacherId=${teacherId}`--%>
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showAutoDismissModal('添加老师成功', true);
                        // 重置选择框
                        document.getElementById('availableTeachersSelect').value = '';
                        // 重新加载已分配老师列表
                        loadAssignedTeachers(courseId);
                        // 重新加载可分配老师列表
                        loadAvailableTeachers(courseId);
                    } else {
                        showAutoDismissModal(data.message || '添加老师失败', false);
                    }
                })
                .catch(error => {
                    console.error('添加老师失败:', error);
                    showAutoDismissModal('添加老师失败: ' + error.message, false);
                });
        });



        // 显示自动消失的Modal
        function showAutoDismissModal(message, isSuccess) {
            const modalElement = document.getElementById('resultModal');
            const resultIcon = document.getElementById('resultIcon');
            const resultTitle = document.getElementById('resultTitle');
            const resultMessage = document.getElementById('resultMessage');

            // 设置图标和样式
            if (isSuccess) {
                resultIcon.className = 'bi bi-check-circle-fill text-success';
                resultTitle.textContent = '成功';
                resultTitle.className = 'mt-3 text-success';
            } else {
                resultIcon.className = 'bi bi-exclamation-triangle-fill text-danger';
                resultTitle.textContent = '错误';
                resultTitle.className = 'mt-3 text-danger';
            }

            // 设置消息内容
            resultMessage.textContent = message;

            // 显示Modal
            const modal = new bootstrap.Modal(modalElement);
            modal.show();

            // 3秒后自动关闭
            setTimeout(function () {
                modal.hide();
            }, 3000);
        }

// 检查URL参数，如果有成功或错误消息则显示
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('success')) {
            showAutoDismissModal(decodeURIComponent(urlParams.get('success')), true);
            // 清理URL参数，避免刷新时重复显示
            setTimeout(function () {
                const url = new URL(window.location);
                url.searchParams.delete('success');
                window.history.replaceState({}, document.title, url);
            }, 3500);
        } else if (urlParams.has('error')) {
            showAutoDismissModal(decodeURIComponent(urlParams.get('error')), false);
            // 清理URL参数，避免刷新时重复显示
            setTimeout(function () {
                const url = new URL(window.location);
                url.searchParams.delete('error');
                window.history.replaceState({}, document.title, url);
            }, 3500);
        }

        // 显示删除确认Modal
        function showDeleteModal(courseId, courseName) {
            document.getElementById('deleteCourseId').textContent = courseId;
            document.getElementById('deleteCourseName').textContent = courseName;

            // 设置确认删除按钮的事件
            const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
            if (confirmDeleteBtn) {
                // 移除所有现有的事件监听器
                const newButton = confirmDeleteBtn.cloneNode(true);
                confirmDeleteBtn.parentNode.replaceChild(newButton, confirmDeleteBtn);

                // 添加新的点击事件
                newButton.addEventListener('click', function () {
                    deleteCourse(courseId);
                });
            }

            // 显示Modal
            const deleteModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
            deleteModal.show();
        }

        // 删除课程功能
        function deleteCourse(courseId) {
            // 关闭确认Modal
            const deleteModal = bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal'));
            if (deleteModal) {
                deleteModal.hide();
            }

            // 使用Ajax发送删除请求
            fetch('${pageContext.request.contextPath}/coursemanage/delete?id=' + courseId, {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('删除响应数据:', data); // 调试用
                    if (data.success) {
                        // 显示成功消息
                        showAutoDismissModal(data.message, true);
                        // 重新加载页面数据
                        setTimeout(function () {
                            location.reload();
                        }, 1500);
                    } else {
                        // 显示错误消息
                        showAutoDismissModal(data.message, false);
                    }
                })
                .catch(error => {
                    console.error('删除出错:', error);
                    showAutoDismissModal('删除过程中发生错误，请重试', false);
                });
        }

        // 将showDeleteModal函数暴露到全局作用域，以便在HTML中调用
        window.showDeleteModal = showDeleteModal;
    });
</script>
<jsp:include page="footer.jsp"/>
